const mongoose = require("mongoose");
const Project = require("../models/project");
const Token = require("../models/token");
const router = require("koa-router")();
const moment = require("moment");
//var url = require('url')
//const $config = require('../../config')

router.get("/view/:_id", async (ctx) => {
  //let referer = ctx.request.header.referer
  //let refererHost = (url.parse(referer)).hostname
  //let baseHost = (url.parse($config.baseURL)).hostname
  // if(refererHost === baseHost){
  let _id = mongoose.mongo.ObjectId(ctx.params._id);
  let project = await Project.findOne({ _id });
  ctx.status = 201;
  await ctx.render("pc", { projectInfo: project });
  //}
  // else{
  //     ctx.status=201
  //     ctx.body = '权限不足'
  // }
});

router.get("/verify/:_id/:token", async (ctx) => {
  // let _id = mongoose.mongo.ObjectId(ctx.params._id);
  let token = ctx.params.token;
  console.log(token);
  // let model = await Token.findOne({ token: token });
  // console.log(token);
  // console.log(model);
  // if (model) {
  // 	let now = moment();
  // 	let before = moment(model.expire);
  // 	if (before.diff(now) > 0) {
  // 		let project = await Project.findOne({ _id: _id });
  // 		ctx.status = 201;
  // 		await ctx.render("pc", { projectInfo: project });
  // 	} else {
  // 		ctx.status = 201;
  // 		ctx.body = "密钥过期了";
  // 	}
  // } else {
  // 	ctx.status = 201;
  // 	ctx.body = { token, model };
  let _id = mongoose.mongo.ObjectId(ctx.params._id);
  let project = await Project.findOne({ _id });
  ctx.status = 201;
  await ctx.render("pc", { projectInfo: project });
  // }
});

//全部场景
router.post("/myProjects", async (ctx) => {
  let author = ctx.state.user._id;
  const search = ctx.request.body.search;
  //const proDatas=await Project.find({ author: author }).ne("isTemplate", true);
  const proDatas = await Project.find({
    author: author,
    title: { $regex: search },
  }).ne("isTemplate", true);
  const data = DelteledData(proDatas);
  ctx.body = {
    data: data || [],
    length: data.length || 0,
    status: Array.isArray(data) ? "true" : "false",
  };
});

//未发布大屏
router.get("/myProjects_unpublish", async (ctx) => {
  let author = ctx.state.user._id;
  const proDatas = await Project.find({ author: author, isPublish: false });
  const data = DelteledData(proDatas);
  ctx.body = {
    data: data || [],
    length: data.length || 0,
    status: Array.isArray(data) ? "true" : "false",
  };
});

//未发布大屏
router.get("/myProjects_publish", async (ctx) => {
  let author = ctx.state.user._id;
  const proDatas = await Project.find({ author: author, isPublish: true });
  const data = DelteledData(proDatas);
  ctx.body = {
    data: data || [],
    length: data.length || 0,
    status: Array.isArray(data) ? "true" : "false",
  };
});

//未发布大屏
router.get("/myProjects_removed", async (ctx) => {
  let author = ctx.state.user._id;
  const proDatas = await Project.find({ author: author, isDelete: true });
  ctx.body = {
    data: proDatas || [],
    length: proDatas.length || 0,
    status: Array.isArray(proDatas) ? "true" : "false",
  };
});

//获取大屏列表
router.post("/myProjects_group", async (ctx) => {
  const author = mongoose.mongo.ObjectId(ctx.state.user._id) || null;
  const groupID = ctx.request.body.params.groupID || null;
  const type = ctx.request.body.params.type;
  const search = ctx.request.body.params.search;
  const sort = ctx.request.body.params.sort || 1;
  const order = {
    all: {
      author: author,
      title: { $regex: search },
      isTemplate: false,
    },
    unpublish: {
      author: author,
      isPublish: false,
      isTemplate: false,
      title: { $regex: search },
    },
    publish: {
      author: author,
      isPublish: true,
      isTemplate: false,
      title: { $regex: search },
    },
    allpublish: {
      isPublish: true,
      isTemplate: false,
      title: { $regex: search },
    },
    remove: {
      author: author,
      isDelete: true,
      isTemplate: false,
      title: { $regex: search },
    },
    ungroup: {
      author: author,
      groupID: "-1",
      isTemplate: false,
      title: { $regex: search },
    },
  }[type];
  const sortRule = [
    { updatedAt: 1 },
    { updatedAt: -1 },
    { created: 1 },
    { created: -1 },
  ][sort - 1];
  const proDatas = order
    ? await Project.find(order).sort(sortRule)
    : await Project.find({
        author: author,
        groupID: groupID,
        isTemplate: false,
        title: { $regex: search },
      }).sort(sortRule);
  // const proDatas = await Project.find({
  // 	author: author,
  // 	groupID: groupID,
  // 	title: { $regex: search },
  // });
  const data = type != "remove" ? DelteledData(proDatas) : proDatas;
  ctx.body = ctx.body = {
    data: data || [],
    length: data.length || 0,
    status: Array.isArray(data) ? "true" : "false",
  };
});

//大屏各场景数量
router.get("/myProjects_amount", async (ctx) => {
  let author = ctx.state.user._id;
  const allAmount =
    (await Project.find({
      author: author,
      isDelete: false,
      isTemplate: false,
    }).countDocuments()) || 0;
  const publishAmount =
    (await Project.find({
      author: author,
      isPublish: true,
      isDelete: false,
      isTemplate: false,
    }).countDocuments()) || 0;
  const allpublishAmount =
    (await Project.find({
      isPublish: true,
      isDelete: false,
      isTemplate: false,
    }).countDocuments()) || 0;
  const unpublishAmount =
    (await Project.find({
      author: author,
      isPublish: false,
      isDelete: false,
      isTemplate: false,
    }).countDocuments()) || 0;
  const removeAmount =
    (await Project.find({
      author: author,
      isDelete: true,
      isTemplate: false,
    }).countDocuments()) || 0;
  const ungroupAmount =
    (await Project.find({
      author: author,
      groupID: "-1",
      isDelete: false,
      isTemplate: false,
    }).countDocuments()) || 0;
  ctx.body = {
    allAmount,
    publishAmount,
    unpublishAmount,
    removeAmount,
    ungroupAmount,
    allpublishAmount,
  };
});

router.post("/modifyName/:_id", async (ctx) => {
  let _id = ctx.params._id;
  let data = ctx.request.body;
  ctx.body = await Project.updateOne(
    { _id },
    { $set: data },
    {
      runValidators: true,
    }
  );
});

router.post("/ckeckpublishpwd", async (ctx) => {
  const _id = ctx.request.body.id;
  const pwd = ctx.request.body.pwd;
  const projectone = await Project.findOne({ _id });
  let state = false;
  if (projectone && projectone.password) {
    projectone.password === pwd ? (state = true) : (state = false);
  }
  ctx.body = state;
});

// router.get('/myPages/count',async ctx=>{
//     let author = ctx.state.user_id
//     author = mongoose.mongo.ObjectId(author)
//     let myList = await Project.find({pageMode:ctx.query.pageMode,author:author}).ne('isTemplate',true)
//     let shareList = await Project.find({pageMode:ctx.query.pageMode,isTemplate:{$ne:true},members:{$elemMatch:{$in:author}}})
//     ctx.body = {
//         my:myList.length,
//         share:shareList.length
//     }
// })

// router.get('/myPublishPages', async ctx=>{
//     let author=ctx.state.user_id
//     author=mongoose.mongo.ObjectId(author)
//     ctx.body=await Project.find({author:author,pageMode:ctx.query.pageMode}).where('isPublish').equals(true)
// })

// router.get('/myPublishPages/count',async ctx=>{
//     let author = ctx.state.user_id
//     author = mongoose.mongo.ObjectId(author)
//     let myList = await Project.find({pageMode:ctx.query.pageMode,author:author}).where('isPublish').equals(true)
//     ctx.body = {
//         my:myList.length
//     }
// })

router.get("/detail/:_id", async (ctx) => {
  let _id = mongoose.mongo.ObjectId(ctx.params._id);
  const findResult = await Project.findOne({ _id });
  ctx.body = findResult;
});

router.post("/add", async (ctx) => {
  let data = ctx.request.body;
  let author = ctx.state.user._id;
  data.groupID = ctx.request.body.groupID;
  data.group = mongoose.mongo.ObjectId(ctx.request.body.group);
  author = mongoose.mongo.ObjectId(author);
  //groupID = mongoose.mongo.ObjectId(groupID);
  ctx.body = await Project.create({
    ...data,
    author: author,
    members: [author],
    isDelete: false,
    _id: mongoose.mongo.ObjectId(),
  });
});

router.post("/copy/:_id", async (ctx) => {
  let _id = mongoose.mongo.ObjectId(ctx.params._id);
  let author = ctx.state.user._id;
  author = mongoose.mongo.ObjectId(author);
  let data = await Project.findOne({ _id });
  ctx.body = await Project.create({
    ...data.toObject(),
    isPublish: false,
    isTemplate: false,
    members: [author],
    author: author,
    _id: mongoose.mongo.ObjectId(),
  });
});

router.post("/update/:_id", async (ctx) => {
  let _id = mongoose.mongo.ObjectId(ctx.params._id);
  let data = ctx.request.body;
  ctx.body = await Project.updateOne(
    { _id },
    { $set: data },
    {
      runValidators: true,
    }
  );
});

router.post("/tempdelete/:_id", async (ctx) => {
  let _id = mongoose.mongo.ObjectId(ctx.params._id);
  const cb = await Project.updateOne({ _id }, { isDelete: true });
  ctx.body = cb;
});

router.post("/tempUndelete/:_id", async (ctx) => {
  let _id = mongoose.mongo.ObjectId(ctx.params._id);
  const cb = await Project.updateOne({ _id }, { isDelete: false });
  ctx.body = cb;
});

router.post("/delete/:_id", async (ctx) => {
  let _id = mongoose.mongo.ObjectId(ctx.params._id);
  ctx.body = await Project.deleteOne({ _id });
});

router.post("/setTemplate/:_id", async (ctx) => {
  let _id = mongoose.mongo.ObjectId(ctx.params._id);
  let data = await Project.findOne({ _id });
  ctx.body = await Project.create({
    ...data.toObject(),
    isTemplate: true,
    isPublish: false,
    members: [],
    _id: mongoose.mongo.ObjectId(),
  });
});

router.get("/myTemplate", async (ctx) => {
  let author = ctx.state.user._id;
  author = mongoose.mongo.ObjectId(author);
  ctx.body = await Project.find({ author: author })
    .where("isTemplate")
    .equals(true)
    .where("isPublish")
    .equals(false);
});

router.post("/publish/:_id", async (ctx) => {
  const _id = mongoose.mongo.ObjectId(ctx.params._id);
  console.log(_id);
  const needpassword = ctx.request.body.needpassword || false;
  const password = ctx.request.body.editpublishinput || "";
  ctx.body = await Project.updateOne(
    { _id },
    { $set: { isPublish: true, needpassword, password } },
    {
      runValidators: true,
    }
  );
});

// router.post('/deleteShareToUser/:_id',async ctx=>{
//     let _id=mongoose.mongo.ObjectID(ctx.params._id)
//     let author=ctx.state.user._id
//     ctx.body=await Project.updateOne({_id},{$pull:{members:author}},{
//         runValidators:true
//     })
// })

// router.post('/publishTemplate/:_id',async ctx=>{
//     let _id=mongoose.mongo.ObjectId(ctx.params._id)
//     let data=await Project.findOne({_id})
//     ctx.body=await Project.create({
//         ...data.toObject(),
//         isTemplate:true,
//         isPublish:true,
//         members:[],
//         _id:mongoose.mongo.ObjectId()
//     })
// })

// router.get('/templateShop/list',async ctx=>{
//     ctx.body=await Project.find({pageMode:ctx.query.pageMode}).where('isTemplate').equals(true).where('isPublish').equals(true)
// })

module.exports = router;

function DelteledData(data) {
  if (Array.isArray(data)) {
    const rebuid = data.filter((item) => {
      item.password = undefined;
      delete item.password;
      if (item.isDelete !== true) {
        return item;
      }
    });
    return rebuid;
  } else {
    return [];
  }
}
